package com.itcast.demo_one.kotlin

class DataCache(private val maxSize: Int = 100) {
    private val cache = mutableMapOf<String, Any>()
    private val accessOrder = mutableListOf<String>()

    fun put(key: String, value: Any) {
        if (cache.size >= maxSize) {
            val oldestKey = accessOrder.removeAt(0)
            cache.remove(oldestKey)
            println("移除旧缓存: $oldestKey")
        }

        cache[key] = value
        accessOrder.add(key) // 添加到最近访问
        println("缓存添加: $key")
    }

    fun get(key: String): Any? {
        return cache[key].also {
            if (it != null) {
                // 更新访问顺序
                accessOrder.remove(key)
                accessOrder.add(key)
            }
        }
    }

    fun size() = cache.size
}

fun main() {
    val cache = DataCache(maxSize = 3)

    cache.put("user1", "Alice")
    cache.put("user2", "Bob")
    cache.put("user3", "Charlie")

    println("获取user2: ${cache.get("user2")}")

    cache.put("user4", "David") // 触发移除旧缓存

    println("缓存大小: ${cache.size()}")
    println("获取user1: ${cache.get("user1")}") // 已被移除
}